class Solution {
public:
    struct ListNode* reverseList(struct ListNode* head)
    {
        struct ListNode* n1, * n2, * n3;
        n1 = nullptr;
        n2 = head;
        if (n2)
            n3 = n2->next;
        while (n2) {
            n2->next = n1;
            n1 = n2;
            n2 = n3;
            if (n3)
                n3 = n3->next;
        }
        return n1;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2)
    {
        if (head1 == nullptr)
            return head2;
        if (head2 == nullptr)
            return head1;
        head1 = reverseList(head1);
        head2 = reverseList(head2);
        ListNode* res = new ListNode(-1);
        ListNode* head = res;
        int carry = 0;
        while (head1 != nullptr || head2 != nullptr || carry != 0)
        {
            int val1 = head1 == nullptr ? 0 : head1->val;
            int val2 = head2 == nullptr ? 0 : head2->val;
            int temp = val1 + val2 + carry;
            carry = temp / 10;
            temp %= 10;
            head->next = new ListNode(temp);
            head = head->next;
            if (head1 != nullptr)
                head1 = head1->next;
            if (head2 != nullptr)
                head2 = head2->next;
        }
        return reverseList(res->next);
    }
};